import os.path
import traceback
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class BasePage:

    def __init__(self, driver):
        self.driver: webdriver.Chrome = driver

    def __find_ele(self, locator: tuple):
        status = self.wait(locator)
        if status:
            try:
                ele = self.driver.find_element(*locator)
                return ele
            except Exception:
                print(traceback.format_exc())

    def wait(self, locator: tuple, timeout=20, poll=1):
        try:
            WebDriverWait(self.driver, timeout, poll).until(EC.visibility_of_element_located(locator))
            return True
        except Exception:
            print(traceback.format_exc())
            return False

    def input(self, locator: tuple, value):
        ele = self.__find_ele(locator)
        if ele:
            ele.send_keys(value)

    def click(self, locator: tuple):
        ele = self.__find_ele(locator)
        if ele:
            ele.click()

    def intoframe(self, locator: tuple):
        ele = self.__find_ele(locator)
        if ele:
            self.driver.switch_to.frame(ele)

    def outoframe(self):
        self.driver.switch_to.default_content()

    def switch_window(self, idx = -1):
        self.driver.switch_to.window(self.driver.window_handles[idx])

    def select(self, locator: tuple, visible_text):
        ele = self.__find_ele(locator)
        if ele:
            select = Select(ele)
            select.select_by_visible_text(visible_text)

    def refresh(self):
        self.driver.refresh()

    def quit(self):
        self.driver.quit()

    def sleep(self, time=2):
        sleep(time)

    def gettext(self, locator):
        ele = self.__find_ele(locator)
        if ele:
            return ele.text

    def get_attribute(self, locator: tuple, attribute_name):
        ele = self.__find_ele(locator)
        if ele:
            value = ele.get_attribute(attribute_name)
            return value

    def execute_js(self, js, ele=None):
        self.driver.execute_script(js, ele)

    def remove_attribute(self, locator, attritubu_name):
        js = f'arguments[0].removeAttribute("{attritubu_name}")'
        ele = self.__find_ele(locator)
        self.execute_js(js, ele)

    def upload_file(self, locator, file_path):
        """
        上传文件功能封装
        :param locator: 上传文件标签定位
        :param file_path: 文件的相对路径
        :return:
        """
        path = os.path.abspath(file_path)
        self.input(locator, path)
